package com.example.testcache1.utils;

import java.io.File;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.util.Log;

/**
 * 浜屾閲囨牱鍥剧墖鍔犺浇
 * 
 * @author bm
 */
public class BitmapUtils {

	/**
	 * @param res
	 * @param id
	 * @param reqWidth
	 *            鎸囧畾鍘嬬缉鍚庡浘鐗囩殑瀹藉害
	 * @param reqHeight
	 *            鍘嬬缉鍚庡浘鐗囩殑楂樺害
	 * @return
	 */
	public static Bitmap decodeResource(Resources res, int id, int reqWidth, int reqHeight) {

		BitmapFactory.Options opts = new BitmapFactory.Options();
		// 鍏堟寚瀹氬彧瑙ｆ瀽鍥剧墖鐨勫ぇ灏�鍒嗚鲸鐜�
		opts.inJustDecodeBounds = true;

		// 姝ゆ椂骞朵笉浼氱湡姝ｇ殑瑙ｆ瀽鎴愪竴寮犲浘鐗囷紝杩斿洖绌虹殑bitmap
		Bitmap bmp1 = BitmapFactory.decodeResource(res, id, opts);

		// 鍙互鐪嬪埌鍥剧墖鐨勫楂�
		// int width = opts.outWidth;
		// int height = opts.outHeight;

		// 鍙互鍒跺畾瑕佸帇缂╁浘鐗囩殑鍊嶆暟
		opts.inSampleSize = calculateInSampleSize(opts, reqWidth, reqHeight);
		opts.inJustDecodeBounds = false;

		Log.i("bm", "鍘嬬缉鐨勫�鏁�   锛�" + opts.inSampleSize);

		Bitmap bmp2 = BitmapFactory.decodeResource(res, id, opts);

		return bmp2;
	}

	public static Bitmap decodeFile(String pathName, int reqWidth, int reqHeight) {
		Bitmap bmp = null;

		Options options = new Options();
		options.inJustDecodeBounds = true;

		BitmapFactory.decodeFile(pathName, options);

		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

		options.inJustDecodeBounds = false;
		bmp = BitmapFactory.decodeFile(pathName, options);

		return bmp;
	}

	/**
	 * @param options
	 * @param reqWidth
	 *            鍥剧墖鍘嬬缉鍚庣殑瀹藉害
	 * @param reqHeight
	 *            鍥剧墖鍘嬬缉鍚庣殑楂樺害
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			final int halfHeight = height / 2;
			final int halfWidth = width / 2;

			// Calculate the largest inSampleSize value that is a power of 2 and
			// keeps both
			// height and width larger than the requested height and width.
			while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
				inSampleSize *= 2;
			}
		}

		return inSampleSize;
	}
}